package framework.base.provider;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

public class DynamicUpdateProvider extends MapperTemplate {

    public DynamicUpdateProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    public String dynamicUpdateById(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.updateTable(entityClass, this.tableName(entityClass)));
        sql.append("<set>");
        sql.append("<foreach collection=\"_parameter.properties().entrySet()\" item=\"value\" index=\"key\" separator=\",\">");
        sql.append("${key} = #{value}");
        sql.append("</foreach>");
        sql.append("</set>");
        sql.append("<where>");
        for (EntityColumn column : EntityHelper.getPKColumns(entityClass)) {
            sql.append(" AND ").append(column.getColumnEqualsHolder("_parameter"));
        }
        sql.append("</where>");
        return sql.toString();
    }

    public String dynamicUpdate(MappedStatement ms) {
        Class<?> entityClass = this.getEntityClass(ms);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.updateTable(entityClass, this.tableName(entityClass)));
        sql.append("<set>");
        sql.append("<foreach collection=\"update.properties().entrySet()\" item=\"value\" index=\"key\" separator=\",\">");
        sql.append("${key} = #{value}");
        sql.append("</foreach>");
        sql.append("</set>");
        sql.append("<where>");
        sql.append("<foreach collection=\"where.properties().entrySet()\" item=\"value\" index=\"key\" separator=\" AND \">");
        sql.append("${key} = #{value}");
        sql.append("</foreach>");
        sql.append("</where>");
        return sql.toString();
    }

}
